import Toast from '@vant/weapp/toast/toast'

class Request {
  constructor(baseURL = '', token = '') {
    this.baseURL = baseURL;
    this.token = token;
  }

  // 通用请求方法
  _request(method, url, data = {}, header = {}) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: this.baseURL + url,
        method: method,
        data: data,
        header: {
          'Content-Type': 'application/json', // 默认的Content-Type
          'Token': this.token,
          ...header // 合并传入的header
        },
        success: (res) => {
          if (res.statusCode >= 200 && res.statusCode < 300) {
            const data = res.data;
            if (data.code === 0) {
              resolve(data);
            } else {
              if (data.code === 401) {
                wx.showToast({
                  title: '登录过期',
                  icon: 'error'
                })
                setTimeout(() => wx.redirectTo({ url: '/pages/login/index' }), 1500)
              } else {
                Toast.fail(data.msg)
              }
              reject(data);
            }
          } else {
            reject({
              message: '请求失败',
              statusCode: res.statusCode,
              data: res.data
            });
          }
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  }
 
  // GET请求
  get(url, params = {}, header = {}) {
    // 如果有查询参数，可以将其拼接到URL上（简单实现，未处理复杂情况）
    const queryString = Object.keys(params).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`).join('&');
    const fullUrl = queryString ? `${url}?${queryString}` : url;
    return this._request('GET', fullUrl, {}, header);
  }
 
  // POST请求
  post(url, data = {}, header = {}) {
    return this._request('POST', url, data, header);
  }
 
  // UPDATE请求（使用PUT方法模拟，实际还是通过method参数指定）
  put(url, data = {}, header = {}) {
    return this._request('PUT', url, data, header); // 在header或服务器端识别为PUT请求
  }
 
  // DELETE请求
  delete(url, data = {}, header = {}) {
    // 通常DELETE请求不带body，但某些API可能需要，这里保留data参数
    return this._request('DELETE', url, data, header);
  }
}

// const request = new Request('http://localhost:8080/mvs')
const request = new Request('http://172.18.30.248:8080/mvs')

export default request